<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>循环遍历加监听</title>
</head>
<body>
    <button>测试1</button>
    <button>测试2</button>
    <button>测试3</button>
<!-- 
  需求：点击某个按钮，提示 '点击的是第 n 个按钮'
 -->

<script type="text/javascript">
    var btns = document.getElementsByTagName('button');
    // for (let i = 0,length = btns.length; i < length; i++) {
    //     btns[i].onclick = function(){
    //         alert('你点击的是第'+(i+1)+'个按钮')
    //     }
    // }
    /*
    for (var i = 0,length = btns.length; i < length; i++) {
        var btn = btns[i]
        btn.index = i
        btn.onclick = function(){
            alert('你点击的是第'+(this.index+1)+'个按钮')
        }
    }
    */

    // 利用闭包
    for (var i = 0,length = btns.length; i < length; i++) {
        (function(i){
            var btn = btns[i]
            btn.onclick = function(){
                alert('你点击的是第'+(i+1)+'个按钮')
            }
        })(i)
    }
</script>
</body>
</html>